﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using Microsoft.Reporting.WebForms;

using SIPO.Library.DataAccess.Report;
using System.Configuration;

using SIPO.Web.Support;

using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DomainObject.Administration.Catalog;

using SIPO.Library.DataAccess.Administration.UserManagement;
using SIPO.Library.DomainObject.Administration.UserManagement;

namespace SIPO.Web.Forms.Transaction
{
    public partial class recPrintInvoiceform : BasePage
    {

        protected override void OnLoad(EventArgs e)
        {
            string invoiceNo = string.Empty;
            string action = string.Empty;
            string email = string.Empty;
            string userid = string.Empty;
            string passwords = string.Empty;

            if (!string.IsNullOrEmpty(Request.Params["invoiceno"]))
            {
                invoiceNo = Request.Params["invoiceno"];
            }
            if (!string.IsNullOrEmpty(Request.Params["action"]))
            {
                action = Request.Params["action"];
            }
            if (!string.IsNullOrEmpty(Request.Params["email"]) && (Request.Params["email"]).ToString() != "undefined")
            {
                email = Request.Params["email"];
            }
            else
            {
                if (base.UserID > 0)
                {
                    recUserRepo recUserDal = new recUserRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                    email = recUserDal.GetById(base.UserID).Email;
                }
            }
            if (!string.IsNullOrEmpty(Request.Params["userid"]))
            {
                userid = Request.Params["userid"];
            }
            if (!string.IsNullOrEmpty(Request.Params["password"]))
            {
                passwords = Request.Params["password"];
            }
            if (!Page.IsPostBack)
            {
                try
                {
                    rptInvoiceRepo invoiceDal = new rptInvoiceRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                    DataTable dt = null;

                    if (action == "registrasi")
                        dt = invoiceDal.GetInvoice(invoiceNo, action);
                    else
                        dt = invoiceDal.GetInvoice(invoiceNo, string.Empty);

                    rptInvoice.Reset();
                    rptInvoice.LocalReport.ReportPath = Server.MapPath("~/reportviewer/rptInvoice.rdlc");
                    ReportDataSource rds = new ReportDataSource();
                    rds.Name = "dsRptInvoice";
                    rds.Value = dt;

                    rptInvoice.LocalReport.DataSources.Clear();
                    rptInvoice.LocalReport.DataSources.Add(rds);
                    rptInvoice.LocalReport.Refresh();

                    dt.Dispose();

                    recParameterRepo paramDal = new recParameterRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                    List<recParameter> parameters = paramDal.GetList();

                    string smtpServer = string.Empty;
                    int smtpPort = 0;
                    string sender = string.Empty;
                    string password = string.Empty;
                    string receiver = email;

                    parameters.ForEach(delegate(recParameter param)
                    {
                        switch (param.ParameterCode.ToLower())
                        {
                            case ("smtpserver"):
                                smtpServer = param.Value;
                                break;
                            case ("smtpport"):
                                smtpPort = int.Parse(param.Value);
                                break;
                            case ("mailsender"):
                                sender = param.Value;
                                break;
                            case ("mailpassword"):
                                password = param.Value;
                                break;
                            default:
                                break;
                        }

                    });

                    string isIndividual = string.Empty;

                    if (base.RegistrationID > 0)
                    {
                        SIPO.Library.DataAccess.Transaction.recRegistrationRepo registrationDal = new Library.DataAccess.Transaction.recRegistrationRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                        SIPO.Library.DomainObject.Transaction.recRegistration registration = registrationDal.GetById(base.RegistrationID);

                        if (registration != null)
                        {
                            if (registration.IsIndividual.HasValue)
                                isIndividual = (registration.IsIndividual.Value == true) ? string.Empty : "perusahaan ";
                        }
                    }

                    string headerMessage = "Kepada YTH Pengurus " + isIndividual + dt.Rows[0][recDebtor.Fields.DebtorName];
                    string senderAlias = "Pesan otomatis Sistem Informasi Penerimaan OJK";

                    Warning[] warnings;
                    string[] streamids;
                    string mimeType;
                    string encoding;
                    string extension;

                    byte[] bytes;
                    bytes = rptInvoice.LocalReport.Render("Pdf", null, out mimeType, out encoding, out extension, out streamids, out warnings);

                    action = string.IsNullOrEmpty(action) ? "Aksi Korporasi" : "Registrasi";

                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
                    {
                        ms.Write(bytes, 0, bytes.Length);
                        // Set the position to the beginning of the stream.
                        ms.Seek(0, System.IO.SeekOrigin.Begin);
                        if (action == "Aksi Korporasi")
                        {
                            Helper.SendEmail(smtpServer, smtpPort, sender, senderAlias, password, receiver, "Surat Setoran " + action,
headerMessage + @"
<br />
Terimakasih anda sudah melakukan aksi korporasi melalui Sistem Informasi Penerimaan OJK.<br/>
Berikut kami sampaikan salinan surat setoran<br/><br/>
Hormat Kami<br/>
Admin Sistem Informasi Penerimaan OJK", ms, "Surat setoran");
                        }
                        else if (userid.ToString() == "" || userid.ToString() == "undefined")
                        {
                            Helper.SendEmail(smtpServer, smtpPort, sender, senderAlias, password, receiver, "Surat Setoran " + action, 
headerMessage + @"
<br/>
Terimakasih anda sudah melakukan registrasi melalui Sistem Informasi Penerimaan OJK.<br/>
Berikut kami sampaikan salinan surat setoran<br/><br/>
Hormat Kami<br/>
Admin Sistem Informasi Penerimaan OJK", ms, "Surat setoran");
                        }
                        else
                        {

                            Helper.SendEmail(smtpServer, smtpPort, sender, senderAlias, password, receiver, "Surat Setoran " + action, "User ID : " + userid + " \n" 
+ headerMessage + @"
<br/>
Terimakasih anda sudah melakukan registrasi melalui Sistem Informasi Penerimaan OJK.<br/>
Berikut kami sampaikan salinan surat setoran<br/><br/>
Hormat Kami<br/>
Admin Sistem Informasi Penerimaan OJK", ms, "Surat setoran");
                        }
                    }
                }
                catch (Exception ex)
                {
                    string innerMsg = string.Empty;
                    if (ex.InnerException != null)
                        innerMsg = ex.InnerException.Message + " ";

                    ClientScript.RegisterClientScriptBlock(typeof(Page), "errMsg", "alert('" + innerMsg + "- " + ex.Message + "')", true);

                }
                finally
                {

                }
            }
        }

    }

}